import os
import re
import argparse
import sys
from pathlib import Path
from colorama import init, Fore, Back, Style

# Initialize colorama
init(autoreset=True)

def remove_py_comments(content):
    """Remove Python style comments"""
    # Remove single line comments
    content = re.sub(r'#.*$', '', content, flags=re.MULTILINE)
    # Remove multi-line comments
    content = re.sub(r'\'\'\'.*?\'\'\'|""".*?"""', '', content, flags=re.DOTALL)
    return content

def remove_c_comments(content):
    """Remove C/C++/Java style comments"""
    # Remove single line comments
    content = re.sub(r'//.*$', '', content, flags=re.MULTILINE)
    # Remove multi-line comments
    content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
    return content

def process_file(file_path):
    """Process a single file to remove comments"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        ext = Path(file_path).suffix.lower()
        if ext in ('.py'):
            content = remove_py_comments(content)
        elif ext in ('.c', '.cpp', '.java'):
            content = remove_c_comments(content)
        else:
            return False
        
        # Remove empty lines and trailing whitespace
        content = '\n'.join(line for line in content.splitlines() if line.strip())
        
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return True
    except Exception as e:
        print(f"Error processing {file_path}: {str(e)}")
        return False

def process_path(path):
    """Process a file or directory"""
    path = Path(path)
    if path.is_file():
        if process_file(path):
            print(f"处理完成: {path}")
    elif path.is_dir():
        # First count all files
        file_count = 0
        for root, _, files in os.walk(path):
            for file in files:
                if Path(file).suffix.lower() in ('.py', '.c', '.cpp', '.java'):
                    file_count += 1
        
        if file_count == 0:
            print("没有找到可处理的代码文件")
            return
        
        print(f"\n共发现 {file_count} 个代码文件\n")
        processed = 0
        
        # Print initial empty progress bars
        print(f"总进度: |{' ' * 40}| 0/{file_count} (0.0%)")
        print("当前文件: |{' ' * 40}| 0%")
        
        for root, _, files in os.walk(path):
            for file in files:
                file_path = os.path.join(root, file)
                if Path(file).suffix.lower() in ('.py', '.c', '.cpp', '.java'):
                    # Move cursor up 2 lines to update progress
                    sys.stdout.write("\033[2A")
                    
                    # Update total progress
                    processed += 1
                    total_progress = processed / file_count
                    total_filled = int(40 * total_progress)
                    total_bar = f"{Fore.GREEN}█" * total_filled + " " * (40 - total_filled)
                    sys.stdout.write(f"\r总进度: |{total_bar}| {processed}/{file_count} ({total_progress:.1%})")
                    
                    # Show current file processing
                    sys.stdout.write(f"\n当前文件: {file_path}\n")
                    sys.stdout.write(f"当前文件: |{Fore.GREEN}{'█' * 40}| 100%")
                    sys.stdout.flush()
                    
                    # Process the file
                    if process_file(file_path):
                        # Move cursor up 2 lines after processing
                        sys.stdout.write("\033[2A")
                        sys.stdout.write(f"\r{Fore.GREEN}✓ {file_path} 处理完成")
                    else:
                        sys.stdout.write("\033[2A")
                        sys.stdout.write(f"\r{Fore.RED}✗ {file_path} 处理失败")
                    
                    # Add spacing between files
                    sys.stdout.write("\n\n")
        print("\n所有文件处理完成")
    else:
        print(f"无效路径: {path}")

def main():
    parser = argparse.ArgumentParser(
        description='删除代码文件中的注释',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog='''使用示例:
  1. 处理单个文件:
     python cmt_deler.py test.py
  
  2. 处理整个目录:
     python cmt_deler.py src/
  
支持的文件类型: .py, .c, .cpp, .java
'''
    )
    parser.add_argument('path', help='要处理的文件或目录路径')
    args = parser.parse_args()
    process_path(args.path)

if __name__ == '__main__':
    main()
